<template>
  <div class="previe-container" v-loading="loading">

    <div class="img-preview">
      <div v-show="continueUploadBtn" class="small-img">
        <!--                <div class="preview-small-img-container">-->

        <!--                    <div v-for="(item, index) in files" :key="item">-->
        <!--                        <div></div>-->
        <!--                        <img style="width: 100%;height: 100%;" :src="createUrl(index)" alt="">-->
        <!--                        <div class="small-text">{{ item.name.substring(0, item.name.indexOf('.')) }}</div>-->
        <!--                    </div>-->
        <!--                </div>-->
        <!-- <el-button @click="continueUpload" style="width: 100%;height: 40px;">继续上传文件</el-button> -->
      </div>
      <div ref="imgContainer" class="img-container">
        <div style="position: relative;" v-for="(item, index) in files" :key="item">
          <img style="width: 100%;height: 70%;" v-if="item.type.includes('image')" class="imgstyle"
            :src="createUrl(index)" alt="">
          <div @dragover="dragOver" @drop="dropImg" style="position: absolute;left: 0;top: 0;right: 0;bottom: 0"></div>
        </div>
        <div style="position: relative;" v-for="(child, i) in totalPageImg" :key="child">
          <!--                <canvas style="border: 1px solid red" :id="`canvas${i}`" :key="child"></canvas>-->
          <img :src="createPDFImgUrl(i)" />
          <div @dragover="dragOver" @drop="dropImg" style="position: absolute;left: 0;top: 0;right: 0;bottom: 0"></div>
        </div>
      </div>
      <div style="width: 150px;" v-show="beginSignBtn">
        <el-button style="position: fixed;right: 10px;top: 0;" @click="beginSign">开始签名</el-button>
        <button style="position: fixed;right: 10px;top: 50px;" draggable="true" @dragstart.stop="onDragstart"
          @dragenter.stop="onDragenter" @dragend.stop="onDragend">
          创建签名区域
        </button>
      </div>
    </div>
    <div v-show="signShow" class="draw">

      <div class="draw-btn">

        <el-button @click="signForText">文字签名</el-button>
        <el-button @click="cleanCanvas">清除</el-button>
        <el-button v-show="exportBtn" @click="exportPdf">导出</el-button>

      </div>
      <canvas ref="canvasSign" width="600" height="200" class="draw-canvas"></canvas>
      <div style="display: flex;width: 600px;" v-show="isTextSign">
        <input v-model="signText" placeholder="请输入签名内容" class="draw-ipt" type="text">
        <el-button @click="clickSignText" style="height: 40px;border-radius: 8px;">确认</el-button>
      </div>
      <el-button @click="clickSubmit" :loading="submitLoading"
        style="width: 600px;height: 40px;margin-top: 20px;">提交</el-button>
      <el-button v-show="domNum.length > 1" @click="nextOne"
        style="width: 600px;height: 40px;margin-top: 20px;">下一个</el-button>
    </div>
  </div>
</template>

<script setup>
import { useFileStore } from '../../store/File'
import { ref, onBeforeMount } from 'vue'
import * as pdfjs from 'pdfjs-dist/build/pdf'
import SignaturePad from "signature_pad";
import { ElMessage } from 'element-plus'
import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf'


pdfjs.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.js', import.meta.url)

// const imgSrc = ref('')

const totalPageNum = ref(0)
const totalPageImg = ref([])
const fileStore = useFileStore()
let imgSrcArr = ref([])
const loading = ref(false)
const files = fileStore.userFile
let usePage = 0
let draw = false
const signShow = ref(false)
const continueUploadBtn = ref(true)
const beginSignBtn = ref(true)
const isTextSign = ref(false)
const signText = ref('')
const submitLoading = ref(false)
const canvasSign = ref(null)
const ctx2 = ref()
const domNum = ref([])
let temp = 0
const exportBtn = ref(false)
const imgContainer = ref(null)
const moveX = ref(0)
const moveY = ref(0)

onBeforeMount(async () => {
  let tempFiles = []
  let pdfFiles = []
  tempFiles = files
  for (let i = 0; i < tempFiles.length; i++) {
    if (!tempFiles[i].type.includes('image')) {
      pdfFiles.push(tempFiles[i])
    }
  }
  // console.log(pdfFiles, "temp")
  if (pdfFiles.length) {
    for (let j = 0; j < pdfFiles.length; j++) {
      const reader = await new FileReader()
      await reader.readAsDataURL(pdfFiles[j])
      reader.onload = await function () {
        pdfjs.getDocument(reader.result).promise.then(res => {
          const pageNum = res.numPages
          for (let k = 0; k < pageNum; k++) {
            totalPageNum.value += 1
            totalPageImg.value.push(totalPageNum.value)
          }
          if (j === 0) {
            for (let k = 1; k < pageNum + 1; k++) {
              res.getPage(k).then(page => {
                const canvas = document.createElement('canvas')

                // const canvas = document.getElementById('canvas'+(k-1))
                // const canvas = waitForCanvas(k-1)
                // console.log(canvas)
                const ctx = canvas.getContext('2d')
                const viewport = page.getViewport({ scale: 1 })
                canvas.height = viewport.height
                canvas.width = viewport.width
                canvas.style.width = viewport.width + 'px'
                canvas.style.height = viewport.height + 'px'
                page.render({
                  canvasContext: ctx,
                  viewport: viewport
                })
                  // canvas.addEventListener('dragover',(e)=>{
                  //   e.preventDefault()
                  // })
                  // canvas.addEventListener('drop',(e)=>{
                  //   const x= e.clientX - canvas.getBoundingClientRect().left
                  //   const y = e.clientY - canvas.getBoundingClientRect().top
                  //   ctx.fillStyle = '#3498db';
                  //   ctx.fillRect(x,y,50,100)
                  // })
                  .promise.then(async (obj) => {
                    const imgUrl = canvas.toDataURL('image/jpeg')
                    const tempObj = {}
                    tempObj.index = k - 1
                    tempObj.imgSrc = imgUrl
                    imgSrcArr.value.push(tempObj)
                  })
              })


            }
          } else {
            let testNum = 1
            for (let l = usePage; l < (usePage + res.numPages); l++) {
              res.getPage(testNum).then(page => {
                // console.log('canvas'+l)
                const canvas = document.createElement('canvas')
                // const canvas = document.getElementById('canvas'+l)
                // console.log(canvas)
                const ctx = canvas.getContext('2d')
                const viewPort = page.getViewport({ scale: 1 })
                // console.log(viewPort,'viewPort')
                canvas.height = viewPort.height
                canvas.width = viewPort.width
                canvas.style.width = viewPort.width + 'px'
                canvas.style.height = viewPort.height + 'px'
                page.render({
                  canvasContext: ctx,
                  viewport: viewPort
                })
                  // canvas.addEventListener('dragover',(e)=>{
                  //   e.preventDefault()
                  // })
                  // canvas.addEventListener('dragover',(e)=>{
                  //   e.preventDefault()
                  // })
                  // canvas.addEventListener('drop',(e)=>{
                  //   const x= e.clientX - canvas.getBoundingClientRect().left
                  //   const y = e.clientY - canvas.getBoundingClientRect().top
                  //   ctx.fillStyle = '#3498db';
                  //   ctx.fillRect(x,y,50,100)
                  // })
                  .promise.then(obj => {
                    canvas.toBlob((blob) => {
                      const url = URL.createObjectURL(blob)
                      const tempObj = {}
                      tempObj.index = l
                      tempObj.imgSrc = url
                      imgSrcArr.value.push(tempObj)
                    }, 'image/png', 0.9)

                  })
              })
              testNum++
            }
          }
          usePage = res.numPages
        })
      }
    }
  }
})

// async function createPDFImgUrl(i){
//
// }
const dragOver = (e) => {
  e.preventDefault()
}
// ---------控制是移动还是叠加----------
// -----已解决----
const dropImg = (e) => {
  let div
  let dragStart = false
  e.preventDefault()
  const parentRect = e.target.getBoundingClientRect();
  if (e.dataTransfer.getData('nodemodel') === 'button') {
    div = document.createElement('div')
    moveX.value = e.clientX - parentRect.left - 50
    moveY.value = e.clientY - parentRect.top - 25
    div.style.width = '100px'
    div.style.height = '50px'
    // div.draggable = true
    div.style.border = '1px solid red'
    div.style.position = 'absolute'
    div.style.left = moveX.value + 'px'
    div.style.top = moveY.value + 'px'
    if (beginSignBtn.value) {
      div.draggable = true
      div.className = 'no-drag'
    } else {
      div.draggable = false
      div.className = ''
    }
    div.addEventListener('dragstart', (event) => {
      // e.preventDefault()
      if (event.target.nodeName !== 'BUTTON') {
        dragStart = true
      }
    })
    div.addEventListener('drag', (event) => {
      if (dragStart) {
        moveX.value = event.clientX - parentRect.left - 50
        moveY.value = event.clientY - parentRect.top - 25
        div.style.left = moveX.value + 'px'
        div.style.top = moveY.value + 'px'
      }
    })
    div.addEventListener('dragend', (event) => {
      dragStart = false
    })
    e.target.appendChild(div)
    domNum.value.push(div)
  }




  // div.style.cursor = 'se-resize'
  // div.style.cursor = 'pointer'


}
const createPDFImgUrl = (i) => {
  const arr = imgSrcArr.value
  // console.log(arr,'arr____________')
  for (let j = 0; j < arr.length; j++) {
    if (arr[j].index === i) {
      return arr[j].imgSrc
    }
  }
}
// console.log(createPDFImgUrl(0),'fbsdhjfhjsadfhujsau')
// const waitForCanvas = (id,callback)=>{
//
//     const canvas = document.getElementById(id);
//   console.log(canvas,'testing__________')
//   console.log(id)
//     if (canvas) {
//       callback(canvas);
//     } else {
//       setTimeout(() => waitForCanvas(id, callback), 100); // 每100毫秒检查一次
//     }
//
// }
const createUrl = (obj) => {
  for (let i = 0; i < files.length; i++) {
    if (i === obj) {
      if (files[i].type.includes('image')) {
        return window.URL.createObjectURL(files[i])
      }
    }
  }
  // console.log(totalPageNum)
  //   for(let i=0;i<totalPageNum.value;i++){
  //     totalPageImg.value.push(i)
  //   }
}

// const handleDrop = (e)=>{
//   e.preventDefault()
//   console.log(e.target,'eeeeeeeeeeeeeeee')
// }
const onDragstart = (e) => {
  e.dataTransfer.setData('nodemodel', 'button')
}

const continueUpload = () => {

}

const beginSign = () => {
  // console.log(imgContainer.value.children[0])
  if (!domNum.value.length) {
    ElMessage.error('请添加签名区域.')
  } else {
    loading.value = true
    setTimeout(() => {
      continueUploadBtn.value = false
      beginSignBtn.value = false
      signShow.value = true
      loading.value = false
      ctx2.value = canvasSign.value.getContext('2d')
      // const rectPosition = canvas.value.getBoundingClientRect()
      // console.log(x,y)
      // ctx.value.scale(3, 3)
      let pad = new SignaturePad(canvasSign.value, { penColor: "#000", maxWidth: 2 })
      pad.addEventListener('beginStroke', () => {
        draw = true
      })
    }, 2000)
  }


}
const cleanCanvas = () => {
  ctx2.value.clearRect(0, 0, canvasSign.value.width, canvasSign.value.height)
  signText.value = ''
}
const clickSignText = () => {
  ctx2.value.font = '70px serif'
  ctx2.value.textAlign = 'center'
  ctx2.value.clearRect(0, 0, canvasSign.value.width, canvasSign.value.height)
  ctx2.value.fillText(signText.value, canvasSign.value.width / 2, canvasSign.value.height / 2 + 11)
}
const signForText = () => {
  isTextSign.value = true
}
const clickSubmit = () => {
  submitLoading.value = true
  const imgUrl = canvasSign.value.toDataURL("image/png")
  for (let i = 0; i < domNum.value.length; i++) {
    if (i === temp) {
      const img = document.createElement('img')
      img.style.width = '100%'
      img.style.height = '100%'
      img.src = imgUrl
      img.className = "no-drag"
      if (domNum.value[i].children.length === 0) {
        domNum.value[i].appendChild(img)
      } else {
        domNum.value[i].replaceChild(img, domNum.value[i].childNodes[0])
      }
      exportBtn.value = true
      submitLoading.value = false
    }
  }

}
const nextOne = () => {
  temp++
}
const exportPdf = () => {

  return new Promise((resolve, reject) => {
    let tempNodes
    tempNodes = imgContainer.value
    // console.log(tempNodes)
    // console.log(tempNodes.children)
    // console.log(tempNodes.children.length)

    for (let i = 0; i < tempNodes.children.length; i++) {
      // console.log(tempNodes.children[i].children);
      // console.log(tempNodes.children[i].lastElementChild);
      if (tempNodes.children[i].lastElementChild.lastElementChild) {
        tempNodes.children[i].lastElementChild.lastElementChild.style.border = 'none'
      }
    }
    html2canvas(tempNodes, {
      background: "#fff",
      allowTaint: true, // 允许渲染跨域图片
      useCORS: true, // 允许跨域
      // 此处可将滚动条隐藏的内容一并用html2canvas截取出来
      height: tempNodes.scrollHeight,
      windowHeight: tempNodes.scrollHeight
    }).then(canvas => {
      let leftHeight = canvas.height
      const a4Width = 595.28
      const a4Height = 841.89
      const a4HeightRef = Math.floor((canvas.width / a4Width) * a4Height)
      let position = 0
      const pageData = canvas.toDataURL("image/png", 1.0)
      const pdf = new jsPDF({
        unit: 'pt',
        format: 'a4',
        orientation: 'p'
      })
      pdf.rect(20, 50, 20, 20)
      let index = 1
      const canvas1 = document.createElement('canvas')
      let height
      pdf.setDisplayMode("fullwidth", "continuous", "FullScreen")
      const pdfName = "sign"

      function createImpl(canvas) {
        if (leftHeight > 0) {
          index++;
          var checkCount = 0;
          //如果整个html高度大于a4纸的高度则开始分页
          if (leftHeight > a4HeightRef) {
            //偏移量加a4纸的高度
            var i = position + a4HeightRef;
            for (i = position + a4HeightRef; i >= position; i--) {
              var isWrite = true;
              for (var j = 0; j < canvas.width; j++) {

                //切断操作应该在这里
                var c = canvas.getContext("2d").getImageData(j, i, 1, 1).data;
                if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
                  isWrite = false;
                  break;
                }
              }
              if (isWrite) {
                checkCount++;
                if (checkCount >= 10) {
                  break;
                }
              } else {
                checkCount = 0;
              }
            }
            height =
              Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
            if (height <= 0) {
              height = a4HeightRef;
            }
          } else {
            height = leftHeight;
          }
          canvas1.width = canvas.width;
          canvas1.height = height;

          var ctx = canvas1.getContext("2d")
          ctx.drawImage(
            canvas,
            0,
            position,
            canvas.width,
            height,
            0,
            0,
            canvas.width,
            height
          );
          if (position != 0) {
            pdf.addPage();
          }
          const margin = 20; // 内边距大小
          if (height < a4Height) {
            pdf.addImage(
              canvas1.toDataURL("image/png", 1.0),
              "PNG",
              margin,
              margin,
              a4Width - margin * 2,
              (a4Width / canvas1.width) * height - margin / 2
            );
          } else {
            pdf.addImage(
              canvas1.toDataURL("image/png", 1.0),
              "PNG",
              margin,
              margin,
              a4Width - margin * 2,
              (a4Width / canvas1.width) * height - margin * 2
            );
          }

          leftHeight -= height;
          position += height;
          if (leftHeight > 0) {
            setTimeout(createImpl, 500, canvas);
          } else {
            pdf.save(pdfName + ".pdf");
            return resolve();
          }
        }
      }

      //当内容未超过pdf一页显示的范围，无需分页
      if (leftHeight < a4HeightRef) {
        const margin = 18; // 内边距大小
        pdf.addImage(
          pageData,
          "PNG",
          margin,
          margin,
          a4Width - margin * 2,
          (a4Width / canvas.width) * leftHeight - margin * 2
        );
        pdf.save(pdfName + ".pdf");
        return resolve();
      } else {
        try {
          pdf.deletePage(0);
          setTimeout(createImpl, 500, canvas);
        } catch (err) {
          return reject();
        }
      }
    })
  })




}
// title.value = fileStore.userFile.name.substring(0, fileStore.userFile.name.indexOf('.'))
// console.log(fileStore.userFile);
// console.log(fileStore.userFile.name.indexOf('.'));
// console.log(fileStore.userFile.name.substring(0, fileStore.userFile.name.indexOf('.')))
// imgSrc.value = window.URL.createObjectURL(fileStore.userFile)
</script>

<style lang="scss" scoped>
.no-drag {
  -webkit-user-drag: none;
}

.draw {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 640px;
  padding: 40px 20px 0 20px;
  height: 450px;
  background-color: red;
  margin-top: 20px;


  .draw-canvas {
    background-color: #fff;
    border-radius: 8px;
    margin: 20px 0;
  }

  .draw-btn {
    display: flex;
    justify-content: flex-start;
    width: 600px;
  }


  .draw-ipt {
    flex: 1;
    height: 40px;
    padding-left: 10px;
    margin-right: 10px;
    outline: none;
    border: none;
    border-radius: 8px;
    border: 1px dashed #ccc;
  }
}

.previe-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  // width: 100%;
  height: 100%;
  padding: 0 20px 0 20px;
  // overflow-y: scroll;

  .img-preview {
    margin-top: 20px;
    width: 100%;
    //height: 100%;
    flex: 1;
    display: flex;
    justify-content: center;
    //align-items: center;
    overflow-y: scroll;
  }

  .img-container {
    //flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0 20px;
    // overflow-y: scroll;
  }

  .imgstyle {
    padding-bottom: 20px;
  }
}

img {

  image-rendering: -moz-crisp-edges;
  /* Firefox */
  image-rendering: -o-crisp-edges;
  /* Opera */
  image-rendering: -webkit-optimize-contrast;
  /*Webkit (non-standard naming) */
  image-rendering: crisp-edges;

  -ms-interpolation-mode: nearest-neighbor;
  /* IE (non-standard property) */

}

.small-img {
  display: flex;
  flex-direction: column;
  width: 200px;
  height: 100%;
  overflow-y: scroll;
  padding: 0 10px;
}

.small-text {
  width: 100%;
  box-sizing: border-box;
  word-break: break-all;
}

.preview-small-img-container {
  flex: 1;
}
</style>
